<template>
  <view>
    <navigationBar ref="navigationBar"/>
    <toast ref="toast"/>
    <loading ref="loading" fullscreen />

    <view class="edit_post_container">
      <view class="textarea-container">
        <u-field
          v-model="textareaValue"
          label-width="0"
          :border-bottom="false"
          :clearable="false"
          maxlength="300"
          placeholder="这一刻的想法···"
          type="textarea"/>
      </view>
      <view class="image-upload-container">
        <uploadGroup
          ref="uploadGroup"
          uploadImageDir="dynamic"
          maxImageCount="3"
          @onImageUploaded="submitPost(arguments)"/>
      </view>
      <view class="menu-container">
        <view
          class="menu-item"
          v-for="item in menuItemList"
          :key="item.id"
          @click="handleMenuItemClick(item.id)">
          <view class="title-icon">
            <i class="fa" :class="item.titleIcon" aria-hidden="true"></i>
          </view>
          <view class="title-text">
            {{ item.titleText }}
          </view>
          <view class="tag" v-show="item.tag">
            {{ item.tag }}
          </view>
        </view>
      </view>
      <view class="button-container">
        <view
          class="btn__default"
          :class="isPostReady ? 'btn__available' : 'btn__unavailable'"
          @click="handlePostBtnClick">
          发布
        </view>
      </view>
    </view>
  </view>
</template>

<script>
    import navigationBar from '@/components/navigationBar/navigationBar.vue';
    import toast from '@/components/toast/toast.vue';
    import loading from '@/components/loading/loading.vue';
    import uploadGroup from '@/components/uploadGroup/uploadGroup.vue';
    import {postDiscuss} from "@/common/js/api/models";

    export default {
        name: "editPost",
        components: {
            navigationBar, toast, uploadGroup, loading
        },
        data() {
            return {
                titleValue: '', //帖子标题的值
                textareaValue: '', //文本域的值
                menuItemList: [
                    {
                        id: 1,
                        titleText: '选择地点',
                        titleIcon: 'fa-map-marker'
                    },
                    {
                        id: 2,
                        titleText: '帖子标题',
                        titleIcon: 'fa-tumblr'
                    }], //菜单项列表
                isPostReady: false, //是否准备发送
                positionInfo: {}, //位置信息
            }
        },
        methods: {
            /**
             * 菜单项点击事件
             * @param itemId {number} 菜单项id
             */
            handleMenuItemClick(itemId) {
                switch (itemId) {
                    case 1:
                        uni.navigateTo({
                            url: "/pages/amap/amap",
                            events: {
                                acceptDataFromOpenedPage: (data) => {
                                    if (data) {
                                        this.positionInfo = {
                                            latitude: data.resultDetails.location.latitude,
                                            longitude: data.resultDetails.location.longitude,
                                            addressName: data.resultDetails.name
                                        }
                                        this.menuItemList[0].tag = data.resultDetails.name;
                                    }
                                },
                            },
                        });
                        break;
                    case 2:
                        this.showTitleEdit = true;
                        break;
                }
            },
            // 发布按钮点击事件
            handlePostBtnClick() {
                this.utils.debounce(() => {
                    if (this.isPostReady) {
                        this.$refs.loading.startLoading();
                        this.$refs.uploadGroup.$refs.upload.upload();
                    }
                });
            },
            // 发布帖子
            submitPost(args) {
                const uploadedImageList = args[0];
                let postContent;
                if (this.positionInfo.latitude) {
                    postContent = `${this.textareaValue}^^^&{la=${this.positionInfo.latitude}&lo=${this.positionInfo.longitude}&n=${this.positionInfo.addressName}}`;
                }
                else {
                    postContent = `${this.textareaValue}`;
                }
                console.log(postContent, uploadedImageList);
                postDiscuss({
                    queryData: {
                        title: this.titleValue,
                        content: postContent,
                        upload: uploadedImageList
                    }
                })
                    .then(res => {
                        console.log(res);
                        this.$refs.loading.stopLoading();
                    })
                    .catch(err => {
                        console.log(err);
                        if (err.data.code === 403) {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            });
                        }
                        else if (err.data.code === 500) {
                            this.$refs.toast.show({
                                text: '请上传图片',
                                type: 'error'
                            });
                        }
                        else if (err.data.code === 200) {
                            this.$refs.toast.show({
                                text: '发布成功',
                                type: 'success'
                            });
                            const postId = err.data.post.id;
                            uni.redirectTo({
                                url: `/pages/postDetail/postDetail?id=${postId}`
                            });
                        }
                        else {
                            this.$refs.toast.show({
                                text: '发布失败',
                                type: 'error'
                            });
                        }
                        this.$refs.loading.stopLoading();
                    });
            },
        },
        mounted() {
            this.$refs.navigationBar.setNavigation({
                titleText: '发帖子',
                backgroundColor: '#fff',
            });
        },
        watch: {
            textareaValue(nval) {
                const lineBreakPosition = nval.indexOf('\n');
                this.isPostReady = nval.replace(/[ ]/g,"").length > 5;
                this.titleValue = (lineBreakPosition === -1 ? nval.substring(0, 15) : nval.substring(0, lineBreakPosition > 15 ? 15 : lineBreakPosition));
                this.menuItemList[1].tag = this.titleValue;
            }
        }
    }
</script>

<style lang="scss" scoped>
  @import 'editPost.scss';
</style>